#include "bitmap.h"

Bitmap::Bitmap(int size):
	Bitmap(size, 0)
{
}

Bitmap::Bitmap(int size, int start):
	m_size(size / 8 + 1),
	m_base(start),
	m_bitmap(new unsigned char[m_size])
{
	memset(m_bitmap, 0x0, m_size);
}

Bitmap::~Bitmap()
{
	delete[] m_bitmap;
	m_bitmap = NULL;
}

int Bitmap::set(int index)
{
	int quo = (index - m_base) / 8;
	assert(quo <= m_size);
	if (quo > m_size)
		return 0;
	int remainder = (index - m_base) % 8;
	unsigned char x = 0x1 << remainder;
	m_bitmap[quo] |= x;
	return 1;
}

int Bitmap::clear(int index)
{
	int quo = (index - m_base) / 8;
	assert(quo <= m_size);
	if (quo > m_size)
		return 0;
	int remainder = (index - m_base) % 8;
	unsigned char x = 0x1 << remainder;
	m_bitmap[quo] &= ~x;
	return 1;
}

int Bitmap::exists(int index)
{
	int quo = (index - m_base) / 8;
	assert(quo <= m_size);
	if (quo > m_size)
		return -1;
	int remainder = (index - m_base) % 8;
	unsigned char x = 0x1 << remainder;
	return (m_bitmap[quo] & x) > 0 ? 1 : 0;
}
